<?php

namespace App\Models\Crm;

use Illuminate\Database\Eloquent\Model;

class ArticleCategory extends Application
{
    //设置白名单
    protected $fillable = ['parent_id', 'name', 'thumb', 'sort_order', 'is_show', 'description', 'created_at', 'updated_at'];
    //设置别名
    protected $table = 'article_categories';

    //一级分类下面有多个二级分类
    static function all_category()
    {
        $categories = ArticleCategory::Sorted()->where('parent_id', 0)->get();
        foreach ($categories as &$category) {
            $category['children'] = ArticleCategory::where("parent_id", $category['id'])->get();
        }
        return $categories;
//            return $this->hasMany('App\Models\Crm\ArticleCategory',
//                'parent_id','id');

    }

    static function cates(){
        $cates = [];
        $parent = ArticleCategory::where('parent_id', 0)->sorted()->get();

        foreach ($parent as &$category) {
            $id = $category['id'];
            $children = ArticleCategory::where('parent_id', $id)->get();
            $cates[$category->name] =$children->pluck('name', 'id')->toArray();
        }

        return $cates;

    }

    //分类下有多个文章，多对多
    public function articles(){
        return $this->belongsToMany('App\Models\Crm\Article');
    }
}
